package com.honvay.cola.auth.web.sms.userdetails;

import com.honvay.cola.auth.core.model.AuthenticatedUser;
import com.honvay.cola.auth.web.sms.SmsUserDetailsService;
import com.honvay.cola.uc.api.UserService;
import com.honvay.cola.uc.api.enums.UserLockStatus;
import com.honvay.cola.uc.api.enums.UserStatus;
import com.honvay.cola.uc.api.model.UserDto;

import java.time.LocalDateTime;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * @author LIQIU
 * created on 2018/12/24
 **/
public class SmsUserDetailsServiceImpl implements SmsUserDetailsService {

	private UserService userService;

	public SmsUserDetailsServiceImpl(UserService userService) {
		this.userService = userService;
	}

	@Override
	public UserDetails loadByPhoneNumber(String phoneNumber) {

		UserDto userDto = userService.findByPhoneNumber(phoneNumber);
		if (userDto == null) {
			throw new UsernameNotFoundException("User " + phoneNumber + " can not be found");
		}
		
		
		AuthenticatedUser authenticatedUser = new AuthenticatedUser();
		authenticatedUser.setId(userDto.getId());
		authenticatedUser.setUsername(userDto.getUsername());
		authenticatedUser.setPassword(userDto.getPassword());
		authenticatedUser.setPhoneNumber(userDto.getPhoneNumber());
		authenticatedUser.setEmail(userDto.getEmail());
		authenticatedUser.setAvatar(userDto.getAvatar());
		authenticatedUser.setEnable(UserStatus.ACTIVE.getValue().equals(userDto.getStatus()));
		authenticatedUser.setLocked(UserLockStatus.LOCKED.getValue().equals(userDto.getLocked()));
		authenticatedUser.setAuthorities(userDto.getAuthorities());
		
		// 账号过期
		if (null != userDto.getAccountExpiredTime() && LocalDateTime.now().isAfter(userDto.getAccountExpiredTime())) {
			authenticatedUser.setAccountNonExpired(false);
		}
		
		// 凭证不过期
		authenticatedUser.setCredentialsNonExpired(true);

		return authenticatedUser;

	}

}
